package com.luck.easyfoodbatch.db;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.luck.easyfoodbatch.App;
import com.luck.easyfoodbatch.entity.Message;
import com.luck.easyfoodbatch.entity.User;
import com.luck.easyfoodbatch.util.HttpUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lmw
 * @ClassName: FindDB
 * @Description: 数据库查询类
 * @date 2014-12-2 下午1:42:15
 */
public class MessageDB {

    private final String TAG = "MessageDB";
    private final String ACTION = "action.refreshMessage";

    private static SQLiteDatabase database;
    private DBManager dBManager;
    private User user;
    private Context mContext;

    public MessageDB(Context context) {
        dBManager = new DBManager(context);
        this.mContext = context;
        user = (User) App.getInstance().readObject(HttpUtil.USER_KEY);
    }


    /**
     * @return void 返回类型
     * @Title: openDataBase
     * @Description: 打开数据库
     * @author lmw
     */
    protected void openDataBase() {
        database = dBManager.openDatabase();
    }

    /**
     * @return void 返回类型
     * @Title: openDataBase
     * @Description: 关闭数据库
     * @author lmw
     */
    protected void closeDataBase() {
        if (null != database) {
            database.close();
        }
    }

    /**
     * 得到所有消息
     *
     * @return
     */
    public List<Message> getByAllMessages() {
        User user = (User) App.getInstance().readObject(HttpUtil.USER_KEY);
        if ((null == database) || !database.isOpen()) {
            openDataBase();
        }

        if (user == null) {
            return new ArrayList<Message>();
        }

        Cursor cur = database
                .rawQuery("SELECT * from message where uid=" + user.getUid() + " order by created_at desc", null);
        try {
            if (cur != null) {
                int num = cur.getCount();
                List<Message> mes = new ArrayList<Message>(num);
                if (cur.moveToFirst()) {
                    do {
                        int mid = cur.getInt(cur
                                .getColumnIndex("mid"));
                        String title = cur.getString(cur.getColumnIndex("title"));
                        int uid = cur.getInt(cur.getColumnIndex("uid"));
                        int is_read = cur.getInt(cur.getColumnIndex("is_read"));
                        String uname = cur.getString(cur.getColumnIndex("uname"));
                        String uavatar = cur.getString(cur.getColumnIndex("uavatar"));
                        String link_url = cur.getString(cur.getColumnIndex("link_url"));
                        String user_type = cur.getString(cur.getColumnIndex("user_type"));
                        int type = cur.getInt(cur.getColumnIndex("type"));
                        int data_type = cur.getInt(cur.getColumnIndex("data_type"));
                        int data_id = cur.getInt(cur.getColumnIndex("data_id"));
                        String data = cur.getString(cur.getColumnIndex("data"));
                        String content = cur.getString(cur.getColumnIndex("content"));
                        int created_at = cur.getInt(cur.getColumnIndex("created_at"));
                        int updated_at = cur.getInt(cur.getColumnIndex("updated_at"));
                        Message message = new Message();
                        message.setMid(mid);
                        message.setTitle(title);
                        message.setUid(uid + "");
                        message.setUname(uname);
                        message.setUavatar(uavatar);
                        message.setType(type);
                        message.setUser_type(user_type);
                        message.setData_type(data_type);
                        message.setData_id(data_id + "");
                        message.setLink_url(link_url);
                        message.setData(data);
                        message.setContent(content);
                        message.setCreated_at(created_at + "");
                        message.setUpdated_at(updated_at + "");
                        message.setIsRead(is_read);
                        mes.add(message);
                    } while (cur.moveToNext());
                }
                return mes;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            database.close();
            cur.close();
        }
        return null;
    }


    /**
     * 得到某个类型的消息
     *
     * @return
     */
    public List<Message> getByTypeMessages(String type) {
        User user = (User) App.getInstance().readObject(HttpUtil.USER_KEY);
        if ((null == database) || !database.isOpen()) {
            openDataBase();
        }

        if (user == null) {
            return new ArrayList<Message>();
        }

        Cursor cur = database
                .rawQuery("SELECT * from message where type= " + type + " and uid=" + user.getUid() + " order by created_at desc", null);
        try {
            if (cur != null) {
                int num = cur.getCount();
                List<Message> mes = new ArrayList<Message>(num);
                if (cur.moveToFirst()) {
                    do {
                        int mid = cur.getInt(cur
                                .getColumnIndex("mid"));
                        String title = cur.getString(cur.getColumnIndex("title"));
                        int uid = cur.getInt(cur.getColumnIndex("uid"));
                        int is_read = cur.getInt(cur.getColumnIndex("is_read"));
                        String uname = cur.getString(cur.getColumnIndex("uname"));
                        String uavatar = cur.getString(cur.getColumnIndex("uavatar"));
                        String link_url = cur.getString(cur.getColumnIndex("link_url"));
                        int types = cur.getInt(cur.getColumnIndex("type"));
                        int data_type = cur.getInt(cur.getColumnIndex("data_type"));
                        int data_id = cur.getInt(cur.getColumnIndex("data_id"));
                        String data = cur.getString(cur.getColumnIndex("data"));
                        String user_type = cur.getString(cur.getColumnIndex("user_type"));
                        String content = cur.getString(cur.getColumnIndex("content"));
                        int created_at = cur.getInt(cur.getColumnIndex("created_at"));
                        int updated_at = cur.getInt(cur.getColumnIndex("updated_at"));
                        Message message = new Message();
                        message.setMid(mid);
                        message.setTitle(title);
                        message.setUid(uid + "");
                        message.setUname(uname);
                        message.setUavatar(uavatar);
                        message.setType(types);
                        message.setUser_type(user_type);
                        message.setData_type(data_type);
                        message.setData_id(data_id + "");
                        message.setLink_url(link_url);
                        message.setData(data);
                        message.setContent(content);
                        message.setCreated_at(created_at + "");
                        message.setUpdated_at(updated_at + "");
                        message.setIsRead(is_read);
                        mes.add(message);
                    } while (cur.moveToNext());
                }
                return mes;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            database.close();
            cur.close();
        }
        return null;
    }

    /**
     * 保存消息
     *
     * @return
     */
    public boolean saveMessage(Message message) {
        if ((null == database) || !database.isOpen()) {
            openDataBase();
        }
        if (!isMessage(message.getMid())) {
            ContentValues values = new ContentValues();
            values.put("uid", user.getUid());
            values.put("mid", message.getMid());
            values.put("link_url", message.getLink_url());
            values.put("title", message.getTitle());
            values.put("uname", message.getUname());
            values.put("uavatar", message.getUavatar());
            values.put("type", message.getType());
            values.put("data_type", message.getData_type());
            values.put("data_id", message.getData_id());
            values.put("data", message.getData());
            values.put("content", message.getContent());
            values.put("created_at", message.getCreated_at());
            values.put("updated_at", message.getUpdated_at());
            values.put("user_type", message.getUser_type());
            values.put("is_read", "0");
            database.insert("message", null, values);
        }
        database.close();
        Log.i(TAG, "消息保存成功");
        // 发送广播 通知有新消息
        Intent intent = new Intent(ACTION);
        mContext.sendBroadcast(intent);
        return true;
    }

    /**
     * 批量保存消息
     *
     * @return
     */
    public boolean saveMessage(List<Message> messages) {
        if ((null == database) || !database.isOpen()) {
            openDataBase();
        }
        for (Message message : messages) {
            if (!isMessage(message.getMid())) {
                ContentValues values = new ContentValues();
                values.put("uid", user.getUid());
                values.put("mid", message.getMid());
                values.put("title", message.getTitle());
                values.put("link_url", message.getLink_url());
                values.put("uname", message.getUname());
                values.put("uavatar", message.getUavatar());
                values.put("type", message.getType());
                values.put("data_type", message.getData_type());
                values.put("data_id", message.getData_id());
                values.put("data", message.getData());
                values.put("content", message.getContent());
                values.put("created_at", message.getCreated_at());
                values.put("updated_at", message.getUpdated_at());
                values.put("user_type", message.getUser_type());
                values.put("is_read", "1");
                database.insert("message", null, values);
            }
        }
        database.close();
        // 发送广播 通知有新消息
        Intent intent = new Intent(ACTION);
        mContext.sendBroadcast(intent);
        Log.i("======================", "消息保存成功");
        return true;
    }


    /**
     * 得到消息id
     *
     * @return
     */
    public String getMessages() {
        if ((null == database) || !database.isOpen()) {
            openDataBase();
        }
        StringBuffer buffer = null;
        Cursor cur = database
                .rawQuery("SELECT * from message where uid='" + user.getUid() + "' order by created_at desc", null);
        try {
            if (cur != null) {
                buffer = new StringBuffer();
                if (cur.moveToFirst()) {
                    do {
                        int mid = cur.getInt(cur
                                .getColumnIndex("mid"));
                        buffer.append(mid).append(",");
                    } while (cur.moveToNext());
                }
                return buffer.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            database.close();
            cur.close();
        }
        return null;
    }


    /**
     * 判断消息是否存在
     *
     * @return
     */
    public boolean isMessage(int mid) {
        User user = (User) App.getInstance().readObject(HttpUtil.USER_KEY);
        if ((null == database) || !database.isOpen()) {
            openDataBase();
        }
        if (user == null) {
            return false;
        }
        StringBuffer buffer = null;
        Cursor cur = database
                .rawQuery("SELECT * from message where mid=" + mid + " and uid=" + user.getUid() + " order by created_at desc", null);
        try {
            if (cur != null) {
                if (cur.moveToFirst()) {
                    do {
                        return true;
                    } while (cur.moveToNext());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //database.close();
            cur.close();
        }
        return false;
    }


    /**
     * 得到所有未读消息数量
     *
     * @return
     */
    public int getByAllMessagesCount() {
        User user = (User) App.getInstance().readObject(HttpUtil.USER_KEY);
        if ((null == database) || !database.isOpen()) {
            openDataBase();
        }
        Cursor cur = database
                .rawQuery("SELECT * from message where is_read = 0 and uid=" + user.getUid(), null);
        int count = cur.getCount();
        cur.close();
        database.close();
        return count;
    }


    /**
     * 得到某个类型未读消息数量
     *
     * @return
     */
    public int getByTypeMessagesCount(String type_id) {
        User user = (User) App.getInstance().readObject(HttpUtil.USER_KEY);
        if ((null == database) || !database.isOpen()) {
            openDataBase();
        }
        Cursor cur = database
                .rawQuery("SELECT * from message where is_read = 0 and type=" + type_id + " and uid=" + user.getUid(), null);
        int count = cur.getCount();
        cur.close();
        database.close();
        return count;
    }


    /**
     * 将消息设为已读
     *
     * @return
     */
    public boolean updateMessageRead(String type_id) {
        if ((null == database) || !database.isOpen()) {
            openDataBase();
        }
        ContentValues values = new ContentValues();
        values.put("is_read", "1");
        database.update("message", values, "type=?" + " and uid=" + user.getUid(), new String[]{type_id});
        database.close();
        return true;
    }

    /**
     * 删除消息
     *
     * @return
     */
    public boolean deleteMessage(String mid) {
        if ((null == database) || !database.isOpen()) {
            openDataBase();
        }
        database.delete("message", "mid=?", new String[]{mid});
        database.close();
        return true;
    }


    /**
     * 得到某个用户下某个类型最新消息
     * msgType 1.系统消息 2.订单消息
     *
     * @return
     */
    public Message getByUidMessage(String msgType) {
        if ((null == database) || !database.isOpen()) {
            openDataBase();
        }
        String sql = "select * from message where type = " + msgType + " and uid=" + user.getUid() + " order by created_at desc limit 0,1";
        Cursor cur = database
                .rawQuery(sql, null);
        try {
            if (cur != null) {
                int num = cur.getCount();
                Message message = null;
                if (cur.moveToFirst()) {
                    do {
                        int mid = cur.getInt(cur
                                .getColumnIndex("mid"));
                        String title = cur.getString(cur.getColumnIndex("title"));
                        int uid = cur.getInt(cur.getColumnIndex("uid"));
                        int is_read = cur.getInt(cur.getColumnIndex("is_read"));
                        String uname = cur.getString(cur.getColumnIndex("uname"));
                        String uavatar = cur.getString(cur.getColumnIndex("uavatar"));
                        String link_url = cur.getString(cur.getColumnIndex("link_url"));
                        int types = cur.getInt(cur.getColumnIndex("type"));
                        int data_type = cur.getInt(cur.getColumnIndex("data_type"));
                        int data_id = cur.getInt(cur.getColumnIndex("data_id"));
                        String data = cur.getString(cur.getColumnIndex("data"));
                        String user_type = cur.getString(cur.getColumnIndex("user_type"));
                        String content = cur.getString(cur.getColumnIndex("content"));
                        int created_at = cur.getInt(cur.getColumnIndex("created_at"));
                        int updated_at = cur.getInt(cur.getColumnIndex("updated_at"));
                        message = new Message();
                        message.setMid(mid);
                        message.setTitle(title);
                        message.setUid(uid + "");
                        message.setUname(uname);
                        message.setUavatar(uavatar);
                        message.setType(types);
                        message.setData_type(data_type);
                        message.setData_id(data_id + "");
                        message.setLink_url(link_url);
                        message.setData(data);
                        message.setUser_type(user_type);
                        message.setContent(content);
                        message.setCreated_at(created_at + "");
                        message.setUpdated_at(updated_at + "");
                        message.setIsRead(is_read);
                    } while (cur.moveToNext());
                }
                return message;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            database.close();
            cur.close();
        }
        return null;
    }

    /**
     * @return void 返回类型
     * @Title: deleteDataBase
     * @Description: 删除数据库
     * @author lmw
     */
    public void deleteDataBase(Context context) {
        context.deleteDatabase("area.db");
    }


}
